package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc2;
import cn.itcast.hotel.pojo.dto.hotelDto;
import cn.itcast.hotel.pojo.vo.Hvo;
import cn.itcast.hotel.resultFul.PageResult;
import cn.itcast.hotel.service.IHotelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    public HotelService() {
        // 默认构造函数，确保Spring CGLIB代理可以正常工作
    }


    @Override
    public PageResult<HotelDoc2> myList(hotelDto dto ) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        query(dto, boolQuery);
        // 使用NativeSearchQueryBuilder构建查询
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
                .withQuery(boolQuery);
                
        // 根据地理位置距离进行查询
        if (dto.getLocation() != null) {
            String[] loc = dto.getLocation().split(",");
            double lat = Double.parseDouble(loc[0]);
            double lon = Double.parseDouble(loc[1]);

            queryBuilder.withSort(SortBuilders
                    .geoDistanceSort("location", new GeoPoint( lat, lon))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS));
        }
//        //添加算分函数
//        queryBuilder.withQuery(QueryBuilders.functionScoreQuery(
//                //基础查询条件
//                QueryBuilders.matchAllQuery(),
//                // function score的数组
//                new FunctionScoreQueryBuilder.FilterFunctionBuilder[] {
//                        // 其中的一个function score 元素
//                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
//                                // 过滤条件
//                                QueryBuilders.termQuery("isAD", true),
//                                ScoreFunctionBuilders.weightFactorFunction(10)
//                        )
//                }
//        ));


        int page = dto.getPage();
        int size = dto.getSize();
        // 确保分页参数有效
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 10;
        }
        queryBuilder.withPageable(PageRequest.of(page - 1, size));
        NativeSearchQuery query = queryBuilder.build();

        SearchHits<HotelDoc2> search = elasticsearchRestTemplate.search(query, HotelDoc2.class);
        List<HotelDoc2> searchHits = search.getSearchHits().stream().map(hit->{
            List<Object> sortValues = hit.getSortValues();
            if (!sortValues.isEmpty()) {
                Object sort =  sortValues.get(0);
                hit.getContent().setDistance(sort);
            }
            return hit.getContent();
        }).collect(Collectors.toList());
        log.info("查询总量{},查询结果：{}", search.getTotalHits(), searchHits);
//        for (SearchHit<HotelDoc2> hit : search.getSearchHits()) {
//            List<Object> sortValues = hit.getSortValues();
//            if ( !sortValues.isEmpty()) {
//                Object sort =  sortValues.get(0);
//                hit.getContent().setDistance(sort);
//                log.info("排序值：{}", sort);
//            }
//        }
        return new PageResult<>(search.getTotalHits(), searchHits);
    }

    @Override
    public Map<String, List<String>> filter(hotelDto dto) {
        Map<String, List<String>> map = new HashMap<>();
       NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.addAggregation(AggregationBuilders.terms("brandAgg").field("brand").size(100));
        queryBuilder.addAggregation(AggregationBuilders.terms("cictyAgg").field("city").size(100));
        queryBuilder.addAggregation(AggregationBuilders.terms("starAgg").field("starName").size(100));

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        query(dto, boolQuery);
        queryBuilder.withQuery(boolQuery);

        NativeSearchQuery query = queryBuilder.build();
        SearchHits<HotelDoc2> search = elasticsearchRestTemplate.search(query, HotelDoc2.class);
        Aggregations aggregations = search.getAggregations();
       if(aggregations!=null) {
           map.put("brand", getAgg("brandAgg", aggregations));
           map.put("city", getAgg("cictyAgg", aggregations));
           map.put("starName", getAgg("starAgg", aggregations));

       }
        return  map;
    }
    public List<String> getAgg(String aggName,Aggregations aggregations) {
        Terms aggregation = aggregations.get(aggName);
        return aggregation.getBuckets().stream().map(Terms.Bucket::getKeyAsString).collect(Collectors.toList());
    }
    public  void query(hotelDto dto,BoolQueryBuilder boolQuery){
        // 判断关键字条件是否为空
        if (StringUtils.isNotBlank(dto.getKey())) {
            boolQuery.must(QueryBuilders.multiMatchQuery(dto.getKey(), "name", "city", "brand", "all"));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        // 添加城市条件（如果 city 不为空）
        if (StringUtils.isNotBlank(dto.getCity())) {
            boolQuery.filter(QueryBuilders.termQuery("city", dto.getCity()));
        }

        // 添加品牌条件（如果 brand 不为空）
        if (StringUtils.isNotBlank(dto.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", dto.getBrand()));
        }

        // 添加明星名称条件（如果 starName 不为空）
        if (StringUtils.isNotBlank(dto.getStarName())) {
            boolQuery.filter(QueryBuilders.termQuery("starName", dto.getStarName()));
        }

        // 添加价格上限条件（如果 maxPrice 不为 null 且大于0）
        if (dto.getMaxPrice() != null && dto.getMaxPrice() > 0) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(dto.getMaxPrice()));
        }

        // 添加价格下限条件（如果 minPrice 不为 null 且大于等于0）
        if (dto.getMinPrice() != null && dto.getMinPrice() > 0) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(dto.getMinPrice()));
        }
    }

    //自动补全
    @Override
    public List<String> suggestion(String pre) {
        SuggestBuilder suggestBuilder = new SuggestBuilder();
        suggestBuilder.addSuggestion("hotelSuggestion",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix( pre)
                        .size(10)
                        .skipDuplicates(true)
        );

        SearchResponse hotel = elasticsearchRestTemplate.suggest(suggestBuilder, IndexCoordinates.of("hotel"));
        return hotel.getSuggest().getSuggestion("hotelSuggestion").getEntries()
                .stream()
                .flatMap(suggestion -> suggestion.getOptions().stream())
                .map(option -> option.getText().toString())
                .collect(Collectors.toList());

    }
}